package com.bo.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.Console;
import com.bo.captcha.model.Captcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.OutputStream;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    // public String code; -> 无法在多线程中进行应用,不可行!!!
    @Autowired
    public Captcha captcha;
    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpServletRequest request,
                           HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        // 定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captcha.getWidth(),captcha.getHeight());
        // 获取code和当前时间
        String code = lineCaptcha.getCode();
        Long time = System.currentTimeMillis();
        // 图形验证码写出,可以写出到文件,也可以写出到流
        lineCaptcha.write(response.getOutputStream());
        // 写入到session
        session.setAttribute(captcha.getSession().getCode(),code);
        session.setAttribute(captcha.getSession().getDate(),time);
        // 关闭流
        response.getOutputStream().close();
    }
    // 0:验证码正确
    // 1:验证码错误
    // 2:验证码过期
    @RequestMapping("/check")
    public Integer check(HttpServletRequest request,String key){
        if(!StringUtils.hasLength(key)){
            return 1;
        }
        Long nowTime = System.currentTimeMillis();
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute(captcha.getSession().getCode());
        Long time = (Long) session.getAttribute(captcha.getSession().getDate());
        // 输入验证码与获取验证码的时间相差大于60秒
        if(nowTime - time > 60000){
            return 2;
        }
        if (!key.equals(code)){
            return 1;
        }
        // 校验正确,清除当前session,防止再次利用
        session.removeAttribute(captcha.getSession().getCode());
        session.removeAttribute(captcha.getSession().getDate());
        return 0;
    }
}
